package io.renren.config.security;

import io.renren.modules.sys.entity.SysUserEntity;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Data
public class SecurityUser implements UserDetails {
    private Long id;
    private String username;
    private String password;
    private String email;
    private String mobile;
    /**
     * 状态  0：禁用   1：正常
     */
    private Integer status;
    private List<String> roles;
    private List<Map<String,String>> menus;

    public SysUserEntity toSysUserEntity() {
        return SysUserEntity.builder()
                .username(this.getUsername())
                .status(this.getStatus())
//                .roleIds("")
                .build();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
//		// 角色，使用@PreAuthorize("hasRole('admin')")
//		SimpleGrantedAuthority admin = new SimpleGrantedAuthority("ROLE_admin");
//		// 操作权限，使用@PreAuthorize("hasAuthority('queryAll')")
//		SimpleGrantedAuthority normal = new SimpleGrantedAuthority("queryAll");
//		return Arrays.asList(admin,normal);
        //我上边要表达的就是，springsecurity在真正比较时用的是role字段，那么如何用一个字段来区分角色和权限呢？就是用的ROLE_

        String[] roles = new String[this.roles.size() + menus.size()];
        int count = 0;

        for (int i = 0; i < this.roles.size(); i++) {
            roles[i] = "ROLE_" + this.roles.get(i);
            count++;
        }
        for (int i = count; i < count + menus.size(); i++) {
            roles[i] = menus.get(i - count).get("perms");
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(roles.length);

        for (String authority : roles) {
            if (StringUtils.isNotEmpty(authority)) {
                grantedAuthorities.add(new SimpleGrantedAuthority(authority));
            }
        }

        return grantedAuthorities;

    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }
}
